const { app, BrowserWindow } = require('electron')
const { join } = require('path')
const path = require('node:path')
const config = require('../controller/config')

require('../controller/desktop-capturer')

const [width = 800, height = 600] = config?.appSize || []

const createWindow = () => {
  const win = new BrowserWindow({
    width,
    height,
    // 该配置能使渲染进程能直接使用nodejs模块(electron主进程……)
    // 十分不建议打开此配置，因为开启后容易通过修改页面内容导致系统攻击(XSS……)
    // webPreferences: {
    //   nodeIntegration: true,//渲染进程启用nodeAPI
    //   contextIsolation:false,//禁止上下文隔离
    // }
    webPreferences: {
      // 定义预加载的js
      preload: path.resolve(__dirname, '../preload/index.js')
    },
    show: false,
  })

  if (process.env.NODE_ENV != 'development') {
    win.loadFile(join(__dirname, '../dist/index.html'))
  } else {
    win.loadURL(process.env.VITE_DEV_SERVER_URL)
  }

  win.on('ready-to-show', () => {
    win.show()
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

